#include "stdafx.h"
#include "dircache.h"

#if _DEBUG
#include <qdebug>
#endif

namespace rco
{

static void _AddDirUpMark(RDirCacheList& outCaches)
{
	DirCachePtr cache;
	cache = new RDirCache;
	cache->bDir = true;
	cache->bEnd = true;
	outCaches.push_back(cache);
	cache.detach();
}

static void RecusiveCacheDirectoryInfo(const QString& filePath, QDir& dir, RDirCacheList& outCaches)
{
	if (!dir.cd(filePath))
		return;

	QFileInfoList fileInfos = dir.entryInfoList();
	DirCachePtr   cache;
	// . & ..
	if (fileInfos.size() <= 2)
		goto _EXIT;

	RDirCache*  pDirCache = nullptr;
	auto it = fileInfos.begin();
	for (++it, ++it; it != fileInfos.end(); ++it)
	{
		cache = new RDirCache;
		outCaches.push_back(cache);
		cache->bDir = it->isDir();
		cache->strPath = it->fileName();

#if _DEBUG
		qDebug() << dir.path();
#endif
		if (cache->bDir)
			RecusiveCacheDirectoryInfo(cache->strPath, dir, outCaches);

		pDirCache = cache.detach();
	}

	if (pDirCache)
	{
		if (!pDirCache->bDir)
		{
			pDirCache->bEnd = true;
			dir.cdUp();
			return;
		}
	}

_EXIT:
	_AddDirUpMark(outCaches);
	dir.cdUp();
}

bool RDirCache::CacheDirectoryInfo(const QString& filePath, RDirCacheList& dirCaches)
{
	QDir dir;
	RecusiveCacheDirectoryInfo(filePath, dir, dirCaches);

	if (dirCaches.size() == 0)
		return false;
	else
		return true;
}

}